package xj.graph2d.app.prop;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.Stroke;
import java.awt.geom.GeneralPath;
import java.awt.geom.Path2D;

import javax.swing.Icon;

import org.jvnet.flamingo.common.icon.ResizableIcon;

import xj.graph2d.DrawAttr;

public class JoinIcon 
  implements ResizableIcon {

  static protected final Stroke simpleStroke = 
    new BasicStroke(1f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER);

  static protected final Stroke miterStroke = 
    new BasicStroke(9f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER);

  static protected final Stroke bevelStroke = 
    new BasicStroke(9f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL);

  static protected final Stroke roundStroke = 
    new BasicStroke(9f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND);

  public JoinIcon() {} 

  public JoinIcon(int width, int height) { 
    this.width = width;
    this.height = height; 
  }

  protected int width = 16;
  protected int height = 16;
  protected Color bg = Color.black; 
  protected Color fg = Color.yellow; 

  protected int join = DrawAttr.LINE_JOIN_MITER;

  public void setDimension(Dimension newDimension) {
    if (newDimension != null) { 
      width = newDimension.width; 
      height = newDimension.height; 
    }
  }

  public void setJoinType(int join) {
    this.join = join;
  }

  public int getJoinType() {
    return join;
  }

  public void paintIcon(Component c, Graphics g, int x, int y) {
    Graphics2D g2 = (Graphics2D) g;
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
			RenderingHints.VALUE_ANTIALIAS_ON);
    Shape clip = g2.getClip();
    g2.clipRect(x, y, width, height);
    Color oldColor = g2.getColor();
    Stroke oldStroke = g2.getStroke();
    //g2.setColor(Color.black);
    g2.setColor(DrawAttr.defaultPenColor);
    switch (join) {
    case DrawAttr.LINE_JOIN_MITER:
      g2.setStroke(miterStroke);
      break;
    case DrawAttr.LINE_JOIN_ROUND:
      g2.setStroke(roundStroke);
      break;
    case DrawAttr.LINE_JOIN_BEVEL:
      g2.setStroke(bevelStroke);
      break;
    }
    int y0 = y + height - 1;
    int y1 = y + (height - 1) / 2;
    GeneralPath line = new GeneralPath(Path2D.WIND_EVEN_ODD, 2);
    line.moveTo(x, y0);
    line.lineTo(x + (width - 1) / 2, y1);
    line.lineTo(x + width - 1, y0);
    g2.draw(line);
    g2.setColor(Color.yellow);
    g2.setStroke(simpleStroke);
    g2.draw(line);
    g2.setStroke(oldStroke);
    g2.setColor(oldColor);
    g2.setClip(clip);
  }

  public int getIconWidth() {
    return width;
  }

  public int getIconHeight() {
    return height;
  }

}
